package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.entity.Categories;
import com.yupi.yuoj.service.CategoriesService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 分类接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/categories")
@Slf4j
public class CategoriesController {

    @Resource
    private CategoriesService categoriesService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建分类（仅管理员）
     *
     * @param categories
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addCategory(@RequestBody Categories categories, HttpServletRequest request) {
        if (categories == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        categories.setStatus(1); // 默认启用
        boolean result = categoriesService.save(categories);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newCategoryId = categories.getId();
        return ResultUtils.success(newCategoryId);
    }

    /**
     * 删除分类（仅管理员）
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteCategory(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        Categories oldCategory = categoriesService.getById(id);
        ThrowUtils.throwIf(oldCategory == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = categoriesService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新分类（仅管理员）
     *
     * @param categories
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateCategory(@RequestBody Categories categories) {
        if (categories == null || categories.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Categories oldCategory = categoriesService.getById(categories.getId());
        ThrowUtils.throwIf(oldCategory == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = categoriesService.updateById(categories);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取分类
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Categories> getCategoryById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Categories category = categoriesService.getById(id);
        if (category == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(category);
    }

    /**
     * 获取所有启用的分类列表
     *
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<Categories>> listCategories() {
        List<Categories> categoryList = categoriesService.lambdaQuery()
                .eq(Categories::getStatus, 1) // 只显示启用的分类
                .orderByAsc(Categories::getSortOrder)
                .orderByAsc(Categories::getId)
                .list();
        return ResultUtils.success(categoryList);
    }

    /**
     * 分页获取分类列表（仅管理员）
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Categories>> listCategoryByPage(@RequestParam long current, @RequestParam long size) {
        Page<Categories> categoryPage = categoriesService.page(new Page<>(current, size));
        return ResultUtils.success(categoryPage);
    }

    /**
     * 根据标识获取分类
     *
     * @param slug
     * @return
     */
    @GetMapping("/slug/{slug}")
    public BaseResponse<Categories> getCategoryBySlug(@PathVariable String slug) {
        if (slug == null || slug.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Categories category = categoriesService.lambdaQuery()
                .eq(Categories::getSlug, slug)
                .eq(Categories::getStatus, 1)
                .one();
        if (category == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(category);
    }

}